<template>
  <div class="app-container" >
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="prompts" prop="prompts">
        <el-input
          v-model="queryParams.prompts"
          placeholder="请输入问题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="生成状态" prop="genStatus" >
        <el-select v-model="queryParams.genStatus"  placeholder="请选择生成状态" clearable>
          <el-option
            v-for="dict in dict.type.qa_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="daterangeCreateTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


    <!--模型选择-->
      <el-select v-model="use_models" multiple placeholder="默认选择全部模型" popper-class="model_select">
        <el-option
          width="650px"
          popper-class="model_select2"
          v-for="dict in dict.type.gpt_model"
          :key="dict.value"
          :label="dict.label"
          :value="dict.value">
        </el-option>
      </el-select>

      <div class="button-new-tags-el" style="height: 100px;width: 90%;padding-top: 10px;">
        <el-col :span="22">
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入prompts,按ctrl +enter快捷发送!"
            @keyup.native.ctrl.enter="sendPrompts(user_prompts)"
            v-model="user_prompts">
          </el-input>

        </el-col>
        <el-button type="primary" :span="2" @click="sendPrompts(user_prompts)"   style="margin-left:15px;height: 57px;">发送</el-button>
      </div>


    <el-row :gutter="10" class="mb8">


      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['article:qContent:remove']"
        >批量删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="openImportTable">
          批量导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['article:qContent:export']"
        >全部导出</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-s-promotion"
          size="mini"
          :disabled="multiple"
          @click="genTask"
        >批量生成勾选数据</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-dropdown icon="el-icon-refresh"  size="mini" split-button type="primary"  @click="genTaskAll">
          一键生成当前未开始
          <el-dropdown-menu slot="dropdown">
            <span style="margin-left: 10px">指定数量：</span>
            <el-input-number v-model="gennum" controls-position="right" @change="handleSelectChange" :min="0" :max="30000"></el-input-number>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-s-promotion"
          size="mini"
          @click="genRetryTask(null,null)"
        >一键重试失败回答</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-row>
          <el-tooltip class="item" effect="dark" content="配置模型参数" placement="top">
            <el-button type="info" size="mini"  @click="openSetModelWin"  icon="el-icon-s-tools" circle></el-button>
          </el-tooltip>
        </el-row>
      </el-col>
      <el-col :span="5">
        <el-alert
          :title=this.balance
          type="warning"
          :closable="false"
          class="showblance"
          show-icon>
        </el-alert>
      </el-col>


      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>


    <el-drawer
      title="模型参数设置"
      :before-close="handleClose"
      :visible.sync="dialog"
      size="70%"
      direction="ltr"
      custom-class="demo-drawer"
      ref="drawer"
    >
      <div class="demo-drawer__content model_setting_panl">

        <el-form ref="form" :model="modelForm" :rules="rules" label-width="180px">
<!--          <el-form-item label="名称" prop="name">-->
<!--            <el-input v-model="modelForm.name" placeholder="请输入名称" />-->
<!--          </el-form-item>-->
          <el-form-item label="系统角色" prop="systemRole">
            <el-input v-model="modelForm.systemRole" type="textarea" placeholder="用于角色生成基调" />
          </el-form-item>

          <el-form-item label="随机性(temperature)" prop="temperature">
            <div class="block">
              <span class="demonstration">值越大，回复越随机</span>
              <el-slider v-model="modelForm.temperature"   :max="1"   :min="0" :step="0.1" :format-tooltip="formatTooltip"></el-slider>
            </div>
            <!--          <el-input v-model="form.temperature" placeholder="请输入随机性" />-->
          </el-form-item>

          <el-form-item label="核采样(topP)" prop="topP">
            <!--          <el-input v-model="form.topP" placeholder="请输入核采样" />-->
            <div class="block">
              <span class="demonstration">与随机性类似，但不要和随机性一起更改</span>
              <el-slider v-model="modelForm.topP" :max="1"   :min="0" :step="0.1" :format-tooltip="formatTooltip"></el-slider>
            </div>
          </el-form-item>
<!--          <el-form-item label="单次回复限制(maxTokens)" prop="maxTokens">-->
<!--            <el-input-number size="mini" :min="1500" :max="16000" :step="200" v-model="modelForm.maxTokens"></el-input-number>-->
<!--          </el-form-item>-->
          <el-form-item label="话题新鲜度(presencePenalty)" prop="presencePenalty">
            <span class="demonstration">值越大，越有可能扩展到新话题</span>
            <el-slider v-model="modelForm.presencePenalty"  :max="1"   :min="0" :step="0.1" :format-tooltip="formatTooltip"></el-slider>
            <!--          <el-input v-model="form.presencePenalty" placeholder="请输入话题新鲜度" />-->
          </el-form-item>
          <el-form-item label="频率惩罚度(frequencyPenalty)" prop="frequencyPenalty">
            <span class="demonstration">值越大，越有可能降低重复字词</span>
            <el-slider v-model="modelForm.frequencyPenalty" :max="1"   :min="0" :step="0.1" :format-tooltip="formatTooltip"></el-slider>
            <!--          <el-input v-model="form.frequencyPenalty" placeholder="请输入频率惩罚度" />-->
          </el-form-item>
<!--          <el-form-item label="备注" prop="remark">-->
<!--            <el-input v-model="modelForm.remark" placeholder="请输入备注" />-->
<!--          </el-form-item>-->
        </el-form>

        <div class="demo-drawer__footer" style="    float: right;margin-right: 10%;margin-bottom: 100px;">
          <el-button @click="cancelForm">取 消</el-button>
          <el-button type="primary" @click="updateModelForm" :loading="loading">{{ loading ? '提交中 ...' : '确 定' }}</el-button>
        </div>
      </div>
    </el-drawer>


    <el-table v-loading="loading" :data="qContentList" :row-class-name="tableRowClassName" @selection-change="handleSelectionChange">

      <el-table-column type="expand">
        <template slot-scope="props">


          <el-form label-position="left" inline class="demo-table-expand" slot="reference">

            <el-form-item v-for="(value,key) in props.row.mapAcontentByModel"  class="a-content-box" row-key=""  :row-class-name="tableRowClassName" :span="24" @change="tableRowClassName">
                <el-tag size="small" class="head-tag">{{ key }}</el-tag>


              <div class="msg-box"  v-for="(item,index) in value" >

                <div class="user-msg"  v-if="index==0" >
                      <div class="acontent-msg msg_problem">
                      <span class="head-user">
                      <i class="el-icon-user-solid"></i>
                      用户：
                    </span>
                        <span class="a-content a-gen">{{ props.row.prompts }}</span>
                      </div>
                </div>

                <div class="user-msg"  v-if="item.qpType=='1'" >
                  <div class="acontent-msg msg_problem">
                      <span class="head-user">
                      <i class="el-icon-user-solid"></i>
                      用户：
                    </span>
                    <span class="a-content a-gen">{{ item.aContent }}</span>
                  </div>
                </div>



                <div class="acontent-msg msg_answer" v-if="item.qpType=='0'" >
                    <span class="head-user">
                      <i class="el-icon-cpu"></i>
                      回答：
                    </span>
                      <span class="a-content a-gen" >{{ item.aContent }}</span>
                      <p class="a-detail">
                        <span class="a-time a-gen-info" >生成时间：{{ item.createTime }}</span>
                        <span class="a-time a-gen-info" >模型信息：{{ item.modelCode }} @ <el-tag size="small">{{ item.modelName }}</el-tag></span>
                        <span class="a-time a-gen-info" >花费token：{{ item.useToken }} </span>

                        <!--                  el-icon-chat-dot-round-->
                        <el-button-group class="a-content-li">
                          <el-tooltip class="item" effect="dark" content="追问" placement="top">
                            <el-button  size="mini" icon="el-icon-chat-dot-round" plain  @click="addPrompts(item.qContentId,item.id)"></el-button>
                          </el-tooltip>

                          <el-tooltip class="item" effect="dark" content="针对空白回答重试" placement="top">
                            <el-button  size="mini" icon="el-icon-refresh" plain  @click="genRetryTask(item.qContentId,item.id)"></el-button>
                          </el-tooltip>
                          <el-tooltip class="item" effect="dark" content="删除此条回答" placement="top">
                            <el-button  size="mini" icon="el-icon-delete" plain  @click="handleAContentDelete(item.id)"></el-button>
                          </el-tooltip>
                        </el-button-group>
                      </p>
                    </div>
              </div>


<!--              <a v-else @click.prevent="handleLink(item)">{{ item.meta.title }}</a>-->
            </el-form-item>

          </el-form>

        </template>
      </el-table-column>


      <el-table-column type="selection" width="50" align="center" />
<!--      <el-table-column label="编号" width="60" align="center" prop="id" />-->
      <el-table-column label="prompts"  min-width="600" align="left" prop="prompts" @change="tableRowClassName">
        <template slot-scope="scope">
          <div>
            {{scope.row.prompts}} <br>
            <el-tag size="small" v-for="(value,key) in scope.row.mapAcontentByModel">{{ key }}</el-tag>
          </div>
<!--          -->
        </template>
<!--      v-for="(value,key) in props.row.mapAcontentByModel"-->
      </el-table-column>
<!--      <el-table-column label="生成状态" align="center" pro
p="genStatus">-->
<!--        <template slot-scope="scope">-->
<!--          <dict-tag :options="dict.type.qa_status" :value="scope.row.genStatus"/>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="生成状态" align="center" prop="genStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.qa_status" :value="scope.row.genStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180"/>
<!--      <el-table-column label="token" align="center" prop="useToken" />-->
      <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width">
        <template slot-scope="scope">
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-edit"-->
<!--            @click="handleUpdate(scope.row)"-->
<!--            v-hasPermi="['article:qContent:edit']"-->
<!--          >修改</el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-promotion"
            :loading="scope.row.genTaskLoading"
            @click="genTask(scope.row)"
          >
            <el-tooltip class="item" v-if="scope.row.aContents.length>0" effect="dark" content="适用于新增选择的模型继续生成答案！" placement="top">
              <span  class="tool-menu">继续生成</span>
            </el-tooltip>

            <el-tooltip class="item"  v-if="scope.row.aContents.length==0" effect="dark" content="适用于导入后未生成答案！" placement="top">
              <span class="tool-menu">生成答案</span>
            </el-tooltip>

          </el-button>

          <el-button
            size="mini"
            type="text"
            v-if="scope.row.aContents.length>0"
            icon="el-icon-s-promotion"
            :loading="scope.row.genTaskLoading"
            @click="addPrompts(scope.row.id,null)"
          >

            <el-tooltip class="item"  effect="dark" content="对该prompts下每个模型的回答继续追问！" placement="top">
              <span  class="tool-menu">追问</span>
            </el-tooltip>

          </el-button>
<!--          <el-button-->
<!--            v-if="scope.row.genStatus==3"-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-s-promotion"-->
<!--            :loading="scope.row.genTaskLoading"-->
<!--            @click="genTask(scope.row)"-->
<!--          >重新生成</el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['article:qContent:remove']"
          >
            <el-tooltip class="item"  effect="dark" content="删除后将无法恢复！" placement="top">
              <span  class="tool-menu">删除</span>
            </el-tooltip>

          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 导入数据包 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="900px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx"
        :headers="upload.headers"
        :action="upload.url+ '?useModels='+form.use_models"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将问题列表Excel文件拖到此处，或<em>点击上传！</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <!--            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据-->
            <el-form ref="form" :model="form" :rules="rules" label-width="0px" style="width: 100%;">
              <el-row>
                <el-form-item label="使用模型"  label-width="100px" prop="use_models">
                  <el-select v-model="form.use_models" multiple placeholder="默认选择全部模型" popper-class="model_select">
                    <el-option
                      width="650px"
                      popper-class="model_select2"
                      v-for="dict in dict.type.gpt_model"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value">
                    </el-option>
                  </el-select>
                </el-form-item>

              </el-row>
            </el-form>

          </div>
          <span>仅允许导入xls格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载包模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm"  :loading="importLoading">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>



</template>

<script>

import { listQContent, getQContent, delQContent, addQContent, updateQContent, startGen,startGenAll,genContentOne,delAContent,showBanlance,genRetryAContent,genAddPrompts,getSetModelInfo,updateFunprompts} from "@/api/article/qContent";
import { getToken } from "@/utils/auth";
import { Loading } from "element-ui";
const baseURL = process.env.VUE_APP_BASE_API;
import websocket from '@/utils/websocket'
export default {
  name: "QContent",
  dicts: ['gpt_model','qa_status', 'gpt_model'],
  data() {
    return {
      // 遮罩层
      loading: true,
      cpmpareloading:false,
      genMessage:"",
      balance:"余额加载中...",
      // 选中数组
      ids: [],
      use_models:[],
      gennum:0,
      user_prompts:null,
      dialog: false,
      // 非单个禁用
      single: true,
      importLoading:false,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 模型比较表格数据
      qContentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "上传数据包",
        use_models:[],

        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        // updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/article/qContent/importData"
      },
      // 总花费token时间范围
      daterangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        prompts: null,
        gennum:0,
        genStatus: null,
        createTime: null,
      },
      // 表单参数
      form: {},
      modelForm:{},
      // 表单校验
      rules: {
        use_models: [
          { required: true, message: "模型未选择", trigger: "blur" }
        ],

      }
    };
  },
  created() {
    this.getList();
    console.log(baseURL);
    websocket.Init();
    this.getWebSocket();
    // let loading =null;
    //  loading = Loading.service({ lock: true, text: "<p>测试生</p>", spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)'});
    // loading.setText("<p>测试\n生</p>")


  },
  methods: {
    /** 查询模型比较列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }
      listQContent(this.queryParams).then(response => {
        this.qContentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      showBanlance(this.queryParams).then(response => {
        let banlce = response.data;
        let showStr = "您的余额："+banlce+"$";
        this.balance = showStr;
      });

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        prompts: null,
        genStatus: null,
        createTime: null,
        createBy: null,
        modelCodes: [],
        gennum:null,
        useToken: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    formatTooltip(val) {
      return val;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleSelectChange(value){
      this.gennum = value;
    },

    tableRowClassName({row, rowIndex}) {
      let beginDate = new Date(row.updateTime);
      let endDate = new Date();
      let minutes =(endDate - beginDate) / (1000 * 60);
      if(minutes<5){
        return 'success-row';
      }
      //
      // if (rowIndex === 1) {
      //   return 'warning-row';
      // } else if (rowIndex === 3) {
      //   return 'success-row';
      // }
      return '';
    },

    sendPrompts(prompts_input){
      let genPs = {
        usemodelCode:this.use_models,
        prompts_input:prompts_input
      }
      let modellist = genPs.usemodelCode;
      if(modellist.length==0){
        this.$message.error('您还没有选择模型，请先选择您所需要使用的模型！');
        return false;
      }
      console.log(genPs);
      genContentOne(genPs).then(() => {
        this.getList();
        // this.$set(row, 'genTaskLoading', false);
        this.$modal.msgSuccess("任务提交成功！");
      }).catch(() => {
        this.$set(row, 'genTaskLoading', false);
      });


    },

    addPrompts(qcontentid,acontentid) {
      this.$prompt('请输入追问内容', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        // this.$message({
        //   type: 'success',
        //   message: '你的邮箱是: ' + value
        // });
        // genAddPrompts

        if(value==null||value==""){
          this.$message({
            type: 'info',
            message: '请输入内容！'
          });
          return;
        }
        let psMap = {
          qcontentid:qcontentid,
          acontentid:acontentid,
          usemodelCode:this.use_models,
          prompts:value
        }
        console.log(psMap)
        genAddPrompts(psMap).then(response => {
          this.getList();
          this.$message({
            type: 'success',
            message: '提交成功！ '
          });
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        });
      });
    },

//执行生成
    genTask(row){

      const ids = row.id || this.ids;
      console.log(row.id)
      let models = [];
      let genPs = {};
      if(!this.isEmpty(row.id)){
        this.$set(row, 'genTaskLoading', true);
        models = this.use_models;
         genPs = {
          usemodelCode:models
        }
      }else{
        genPs = {
          usemodelCode:[]
        }
      }

      console.log(models)

      console.log(row)
      console.log(models)
      let tipsContent = "";
      if(!this.isEmpty(row.id)&&row.aContents.length!=0&&models.length==0){
        this.$message({
          message: '需选择新的模型在点击继续生成！',
          type: 'warning'
        });
        this.$set(row, 'genTaskLoading', false);
        return;
      }
      if(models.length==0){
        tipsContent = "您当前未选择生成模型，将使用导入时选择模型生成，是否继续？";
      }else{
        const resultString = models.join(',');
        tipsContent = "您将使用["+resultString+"]这些模型，来生成内容，是否继续？";
      }
      this.$modal.confirm(tipsContent).then(function() {
        return startGen(ids,genPs);
      }).then(() => {
        this.activeName= 'all';
        this.queryParams.genStatus = null;
        this.use_models = [];
        this.getList();
        this.$set(row, 'genTaskLoading', false);
        this.$modal.msgSuccess("任务提交成功");


      }).catch(() => {
        this.$set(row, 'genTaskLoading', false);
      });
    },
    genTaskAll(){
      // startGenAll
      console.log(typeof this.queryParams);
      let genps = this.queryParams;
      console.log(genps)
      genps.gennum = this.gennum;
      genps.genStatus = genps.genStatus==null?"0":genps.genStatus.toString();
      genps.usemodelCode =this.use_models;


      console.log(genps)
      this.$modal.confirm('确定执行任务吗？').then(function() {
        return startGenAll(genps);
      }).then(() => {
        this.$modal.msgSuccess("任务提交成功");
        this.activeName= 'all';
        this.queryParams.genStatus = null;
        this.use_models = [];
        this.getList();
      }).catch(() => {
      });

    },
    openSetModelWin(){
      this.dialog = true;
      getSetModelInfo().then(response => {
        console.log(response)
        this.modelForm = response.data;
      });
    },
    //重试空白
    genRetryTask(qContentId,aContentId){
      let retry = {};
      if(qContentId!="undefind"&&qContentId!=null){
        retry = {
          qContentId:qContentId,
          aContentId:aContentId
        }
      }

      console.log(retry)

      this.$modal.confirm('确定执行重试任务吗？').then(function() {
        return genRetryAContent(retry);
      }).then(() => {
        this.$modal.msgSuccess("任务提交成功");
        this.queryParams.genStatus = null;
        this.getList();
      }).catch(() => {
      });

    },
    fullScreen(txtValue,type) {
      console.log("更新消息内容")
      let loading =null;
      if(type=="open"){

        loading = Loading.service({ lock: true, text: txtValue, spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)'});
        loading.setText(`${ txtValue }`)
        // loading = this.$loading({
        //   lock: true,
        //   text: txtValue,
        //   spinner: 'el-icon-loading',
        //   background: 'rgba(0, 0, 0, 0.7)'
        // });
      }else{
        console.log("close");
        // this.$nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
        //   loading.close()
        // });
        setTimeout(() => {
          loading = Loading.service({ lock: true, text: txtValue, spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)'});
          loading.close();
        }, 2000);
      }


    },

    /** 打开导入表弹窗 */
    openImportTable() {
      // this.$refs.import.show();
      this.reset();
      this.upload.title = "待提问内容上传";
      this.upload.open = true;
    },

    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.importLoading = true;
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.importLoading = false;
      this.getList();
    },

    // 提交上传文件
    submitFileForm() {
      this.importLoading = true;
      console.log(this.form)
      if(this.form.use_models.length==0){
        this.$message({
          message: '您还未选择需要使用的模型！',
          type: 'warning'
        });
        this.importLoading = false;
        return;
      }
      this.$refs.upload.submit();
    },

    /** 下载模板操作 */
    importTemplate() {
      // this.download('system/user/importTemplate', {
      // }, `user_template_${new Date().getTime()}.xlsx`)
      this.$download.zip("/common/download?fileName=prompts.xlsx&delete=false" , "temp.xlsx");

    },


    // websocket 接受消息
    getWebSocket() {
      let self = this;
      // websocket.getWebSocket()这个是websocket里面方法返回ws对象（websocket.js）
      try {

        let ws = websocket.getwebsocket();
        console.log(ws)
        ws.onmessage = function(e){
          console.log('msg:' + e.data);
          let msg = e.data;
          if(typeof msg == 'string'){
            let obj = "";
            try {
              obj =  JSON.parse(msg);
            }catch (e) {
              console.log(e)
            }
            if(typeof obj == 'object' && obj){
              console.log("json",obj);
              self.setBtnLoading(msg)
            }else{
              console.log("非json")
            }
          }else{
            console.log(msg)
          }

        }
      } catch (e) {
        console.log(e)
      }

    },

    setBtnLoading(msg){
      let obj = JSON.parse(msg);
      let message = obj.message;
      let percentage = obj.percentage;
      let genstatus = obj.status;
      let acontentid = obj.acontentId;
      console.log(obj)
      if(genstatus=="end"){
        this.fullScreen(message,'close');
      }else{
        this.fullScreen(message,'open');
      }
      this.getList();
    },



    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加模型比较";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getQContent(id).then(response => {
        this.form = response.data;
        this.form.modelCodes = this.form.modelCodes.split(",");
        this.open = true;
        this.title = "修改模型比较";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.modelCodes = this.form.modelCodes.join(",");
          if (this.form.id != null) {
            updateQContent(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addQContent(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleAContentDelete(id){
      this.$modal.confirm('是否确认该条回答？').then(function() {
        return delAContent(id);
      }).then(() => {
        this.getList();
        // this.qContentList = this.collection.map(item => {
        //   item.aContents = item.aContents.filter(aContent => aContent.id !== id);
        //   return item;
        // });
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      console.log(row)
      this.$modal.confirm('是否确认删除该数据项，并删除其所有回答内容？').then(function() {
        return delQContent(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('article/qContent/export', {
        ...this.queryParams
      }, `qContent_${new Date().getTime()}.xlsx`)
    },
    isEmpty(str){
      if (!str || str == "undefined" || str == "null" ||str == null) {
        return true;
      }else{
        return false;
      }
    },

    handleClose(done) {
      if (this.loading) {
        return;
      }
      this.loading = false;
      this.dialog = false;
      clearTimeout(this.timer);
      // this.$confirm('确定要提交表单吗？')
      //   .then(_ => {
      //     this.loading = true;
      //     this.timer = setTimeout(() => {
      //       done();
      //       // 动画关闭需要一定的时间
      //       setTimeout(() => {
      //         this.loading = false;
      //       }, 400);
      //     }, 2000);
      //   })
      //   .catch(_ => {});
    },
    cancelForm() {
      this.loading = false;
      this.dialog = false;
      clearTimeout(this.timer);
    },
    updateModelForm(){
      updateFunprompts(this.modelForm).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.loading = false;
        this.dialog = false;
        this.getList();
      });
    }


  }
};
</script>
<style>

  .el-select{
    width: 90%;
  }
  .button-new-tags-el{
    margin-bottom: 0px;
  }

   .demo-table-expand {
     font-size: 0;
   }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }

  .acontent-msg{
    position: relative;
    display: inline-block;
    margin: 10px 0 0 0;
    padding: 1px 14px;
    min-width: 120px;
    max-width: 100%;
    color: #555;
    font-size: 16px;
    background: #2f54eb1a;
    border-radius: 10px;
  }


  /*.acontent-msg:before{*/
  /*  content: "";*/
  /*  position: absolute;*/
  /*  top: 50%;*/
  /*  left: -29px;*/
  /*  margin-top: -15px;*/
  /*  border: 15px solid transparent;*/
  /*  border-right: 15px solid #2f54eb1a;*/
  /*}*/

  .arrowbox1-left p {
    margin: 0;
    padding: 0;
  }


  .a-content{
    margin-left: 12px;
  }
  .a-time {
    /* width: 98% !important; */
    color: #8a8ba1;
  }
  .a-content-box{
    width: 98% !important;
    border: 2px solid rgb(19 22 232 / 12%);
    /*filter: drop-shadow(0px 42px 76px #00042B);*/
    border-radius: 10px;
    /* text-align: center; */
    padding: 9px 12px;
    margin: 10px;
  }
  .a-detail {
    border-left: 4px solid #2f54eb;
    background: #d7dcef;
    padding-right: 20px;
    border-top-right-radius: 5px;
    border-bottom-right-radius: 5px;
    /* width: 98%; */
  }
  .a-gen-info {
    margin-left: 20px;

  }
  .el-table .success-row {
    background: #f0f9eb;
  }
  .a-content-li{
    float: right;
    margin-top: 4px;
    margin-left: 50px;
  }
  .showblance{
    margin-left: 30%;
  }
  .el-select-dropdown__item{
    float: left;
  }
  .el-select-dropdown{
    left: 30px;
    right: 30px;
  }
  .head-tag{
    position: absolute;
    margin-top: -10px;
  }

  .msg_problem{
    background: #eee;
    margin-top: 22px;
  }

  .model_setting_panl .el-form-item__content{
    margin-right: 100px;
  }

  .msg_answer{

  }

</style>
